package com.wy.demo.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wy.demo.service.ScreenshotServiceCall;
import com.wy.demo.vo.ScreenshotBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ScreenshotServiceCallImpl implements ScreenshotServiceCall {
    @Value("${screenshot.server.url}")
    private String screenshotServerUrl;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ScreenshotBean screenshot(ScreenshotBean request) {
        log.info("开始调用截图服务: {} -> {}", request.getHtmlFilePath(), request.getOutputImagePath());

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(screenshotServerUrl + "/screenshot");
            httpPost.setHeader("Content-Type", "application/json");

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("htmlFilePath", request.getHtmlFilePath());
            requestBody.put("outputImagePath", request.getOutputImagePath());

            if (request.getOptions() != null) {
                Map<String, Object> options = new HashMap<>();
                options.put("width", request.getOptions().getWidth());
                options.put("height", request.getOptions().getHeight());
                options.put("deviceScaleFactor", request.getOptions().getDeviceScaleFactor());
                options.put("fullPage", request.getOptions().getFullPage());
                options.put("quality", request.getOptions().getQuality());
                options.put("type", request.getOptions().getType());
                options.put("autoSize", request.getOptions().getAutoSize());
                requestBody.put("options", options);
            }

            String jsonBody = objectMapper.writeValueAsString(requestBody);
            httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                if (response.getStatusLine().getStatusCode() == 200) {
                    // 解析成功响应
                    Map<String, Object> result = objectMapper.readValue(responseBody, Map.class);
                    request.setSuccess((Boolean) result.get("success"));
                    request.setTime(((Number) result.get("time")).longValue());

                    log.info("截图服务调用成功，耗时: {}ms", request.getTime());
                    return request;
                } else {
                    // 解析错误响应
                    Map<String, Object> errorResult = objectMapper.readValue(responseBody, Map.class);
                    request.setSuccess(false);
                    request.setError((String) errorResult.get("error"));

                    log.error("截图服务调用失败: {}", request.getError());
                    return request;
                }
            }

        } catch (IOException e) {
            log.error("调用截图服务时发生异常", e);
            request.setSuccess(false);
            request.setError("调用截图服务异常: " + e.getMessage());
            return request;
        }
    }

    @Override
    public boolean isServiceHealthy() {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(screenshotServerUrl + "/health");
            httpGet.setHeader("Accept", "application/json");

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    Map<String, Object> healthStatus = objectMapper.readValue(responseBody, Map.class);

                    String status = (String) healthStatus.get("status");
                    boolean isHealthy = "ok".equals(status);

                    log.debug("截图服务健康检查结果: {}", isHealthy);
                    return isHealthy;
                } else {
                    log.warn("截图服务健康检查失败，状态码: {}", statusCode);
                    return false;
                }
            }

        } catch (Exception e) {
            log.error("截图服务健康检查异常", e);
            return false;
        }
    }
}
